package com.axios.core.config.ssl;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

import com.axios.core.tool.UrlTool;
import com.axios.core.tool.ssl.SSLTool;
import com.axios.exception.IORuntimeException;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;

/**
 * [自定义支持协议类型的SSLSocketFactory](Customize sslsocketfactory that supports protocol types)
 * @description zh - 自定义支持协议类型的SSLSocketFactory
 * @description en - Customize sslsocketfactory that supports protocol types
 * @version V1.0
 * @author XiaoXunYao
 * @since 2021-11-17 13:29:57
 */
public class CustomProtocolsSSLFactory extends SSLSocketFactory {

	private final String[] protocols;
	private final SSLSocketFactory base;

	public CustomProtocolsSSLFactory(String... protocols) throws IORuntimeException {
		this.protocols = protocols;
		this.base = SSLTool.createSSLContext(null).getSocketFactory();
	}

	@Override
	public String[] getDefaultCipherSuites() {
		return base.getDefaultCipherSuites();
	}

	@Override
	public String[] getSupportedCipherSuites() {
		return base.getSupportedCipherSuites();
	}

	@Override
	public Socket createSocket() throws IOException {
		final SSLSocket sslSocket = (SSLSocket) base.createSocket();
		resetProtocols(sslSocket);
		return sslSocket;
	}

	@Override
	public SSLSocket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
		final SSLSocket socket = (SSLSocket) base.createSocket(s, host, port, autoClose);
		resetProtocols(socket);
		return socket;
	}

	@Override
	public Socket createSocket(String host, int port) throws IOException {
		final SSLSocket socket = (SSLSocket) base.createSocket(host, port);
		resetProtocols(socket);
		return socket;
	}

	@Override
	public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException {
		final SSLSocket socket = (SSLSocket) base.createSocket(host, port, localHost, localPort);
		resetProtocols(socket);
		return socket;
	}

	@Override
	public Socket createSocket(InetAddress host, int port) throws IOException {
		final SSLSocket socket = (SSLSocket) base.createSocket(host, port);
		resetProtocols(socket);
		return socket;
	}

	@Override
	public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
		final SSLSocket socket = (SSLSocket) base.createSocket(address, port, localAddress, localPort);
		resetProtocols(socket);
		return socket;
	}

	/**
	 * [重置可用策略](Reset available policies)
	 * @description zh - 重置可用策略
	 * @description en - Reset available policies
	 * @version V1.0
	 * @author XiaoXunYao
	 * @since 2021-11-17 13:29:25
	 * @param socket SSLSocket
	 */
	private void resetProtocols(SSLSocket socket) {
		if (UrlTool.isNotEmpty(this.protocols)) {
			socket.setEnabledProtocols(this.protocols);
		}
	}
}
